<?php
/*
 * Forescore
 * A golf scoring and analysis app
 * 
 * @license   MIT License
 * @package   Forescore
 * @author    $Author: brian@brianvoss.com $
 * @version   $Id: Base.php 9 2012-11-03 18:58:09Z brian@brianvoss.com $
 * @lastrevision   $Date: 2012-11-03 11:58:09 -0700 (Sat, 03 Nov 2012) $
 * @filesource     $URL: https://forescore.googlecode.com/svn/trunk/library/Forescore/Model/Base.php $
 */

class Forescore_Model_Mapper extends Zend_Db_Table_Abstract {
	/**
	 * @var String 
	 */
	protected $model_class;
	/**
	 * @public 
	 */
	public function __construct( $model_class)
	{
		parent::__construct();
		$this->model_class = $model_class;
	}
	/**
	 * Factory method to turn an array of
	 * of database rows into an array
	 * of instantiated objects
	 * @param mixed $data
	 * @param bool $id_indexes
	 * @return array
	 */
	public function factory($data, $id_indexes=false)
	{
		$return = null;
		if (!is_object($data))
		{
			return false;
		}
		switch( get_class($data))
		{
			case "Zend_Db_Table_Rowset":
				$return = array();
				foreach ($data as $row) {
					$obj = $this->factoryItem($row);
					if ( $id_indexes )
					{
						try
						{
							$id = $obj->getId();
							$return[$id] = $obj;
							continue;
						}
						catch ( Exception $e)
						{
							// just push to array
						}
					}
					array_push($return, $obj);
				}
				return $return;
				break;
			case "Zend_Db_Table_Row":
				return $this->factoryItem($data);
				break;
		}
	}

	/**
	 * Factory method to turn one
	 * database row into an
	 * instantiated object
	 * @param Zend_Db_Table_Row $item
	 * @return mixed
	 */
	public function factoryItem(Zend_Db_Table_Row $item)
	{
		$arr_data = $item->toArray();
		$object = new $this->model_class($arr_data);
		return $object;
	}
	/**
	 * Factory method to find a record by
	 * id and return an instantiated object
	 * @param int $id
	 * @return model_class
	 */
	public final function getById($id)
	{
		// Query the persistence layer
		$result = $this->find($id);
		return $this->factory($result);
	}
	
}